#include <2025Linux.h>
int main(int argc, char *argv[])
{
    // ./1_server 192.168.72.128 12345
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");
    int flag = 1;
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    ERROR_CHECK(ret,-1,"setsockopt");
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    ret = bind(sockfd,(struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(sockfd, 10);
    ERROR_CHECK(ret,-1,"listen");

    //做两次accept
    int netfd1,netfd2;
    netfd1 = accept(sockfd,NULL,NULL);
    printf("client1 is connected!netfd1 = %d\n", netfd1);
    netfd2 = accept(sockfd,NULL,NULL);
    printf("client2 is connected!netfd2 = %d\n", netfd2);
   
    // 准备select 监听netfd1和netfd2
    fd_set readyset;
    char buf[4096];
    while(1){
        FD_ZERO(&readyset);
        FD_SET(netfd1,&readyset);
        FD_SET(netfd2,&readyset);
        select(netfd2+1,&readyset,NULL,NULL,NULL);
        if(FD_ISSET(netfd1,&readyset)){
            memset(buf,0,sizeof(buf));
            recv(netfd1,buf,sizeof(buf),0);
            send(netfd2,buf,strlen(buf),0);
        }
        if(FD_ISSET(netfd2,&readyset)){
            memset(buf,0,sizeof(buf));
            recv(netfd2,buf,sizeof(buf),0);
            send(netfd1,buf,strlen(buf),0);
        }
    }
    return 0;
}

